<?php


namespace App\Common;


use App\Utils\DMSQL;
use App\Utils\Logger;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class SystemLog
{

    private $db = null;


    public function __construct()
    {
        $this->db = new DMSQL();
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        $this->db = null;
    }

    /**
     * 系统异常日志记录
     * @param string $content 异常内容
     * @param string $postion
     */
    public function addLog(string $content, string $postion="")
    {
        // TODO: Implement addLog() method.
        if(empty(session('uid'))){
            $uid = "null";
        }else{
            $uid = authcode(session('uid'));
        }

        if(empty(session('username'))){
            $username = "null";
        }else{
            $username = authcode(session('username'));
        }
        $data['uid'] = $uid;
        $data['username'] = $username;
        $data['ipaddress'] = request()->ip();
        $data['content'] = $content;
        $data['created_at'] = time();
        $data['params'] = json_encode(request()->all());
        $data['position'] = request()->url(). "|".request()->method() ."|";
        $result = $this->db->table('system_error')->insert($data);
        $this->fileLog($data);
        if($result == 10001){
            Log::info($result['msg']);
        }
    }

    public function fileLog(array $data)
    {
        $content = "";
        $content .= date("Y-m-d H:i:s",$data['created_at']) . "     ";
        $content .= $data['uid'] . "        ";
        $content .= $data['username'] . "       ";
        $content .= $data['ipaddress'] . "      ";
        $content .= $data['content'] . "        ";
        $content .= array2string(request()->all()) . "     ";
        $content .= request()->url(). "|".request()->method() ."|";
        $file = date("Ymd",time()).".log";
        Storage::disk('syslog')->append($file,$content);
        Log::info($content);
    }

    //请求日志
    public function urlLog(){
        $data['type'] = 1;
        $data['url']  = request()->url();
        $data['ipaddress'] = request()->ip();
        $data['method'] = request()->method();
        $data['params'] = json_encode(request()->all());
        $data['created_at'] = date("Y-m-d:H:i:s",time());
        //$result = $this->db->table('REQUEST_LOG')->insert($data);
        $str = implode(",",$data);

        $file = authcode(session('username'))."---".date("Ymd",time())."request.log";
        Storage::disk('requestlog')->append($file,$str);
    }

    //登录日志
    public function loginLog(array $data){
        $data['logintime'] = date("Y-m-d H:i:s",$data['logintime']);
        $str = implode(",",$data);
        $file = date("Ymd",time())."login.log";
        Storage::disk('loginlog')->append($file,$str);
    }
}
